package com.wee.aircoach_user;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.toolbox.ImageLoader;
import com.bigtotoro.util.SharedPreferencesUtil;
import com.bigtotoro.widgets.listview.HorizontalListView;
import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chatuidemo.DemoHXSDKHelper;
import com.easemob.chatuidemo.activity.ChatActivity;
import com.easemob.chatuidemo.utils.UserUtils;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.wee.adapter.CoachImgsAdapter;
import com.wee.entity.Coach_details;
import com.wee.entity.IsMy_plan;
import com.wee.entity.MD5Util;
import com.wee.imageforBigger.image.ImagePagerActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
     * 教练详细信息界面
     */
    public class CoachInfoActivity extends Activity implements View.OnClickListener {
        private  Coach_details details;
        private ImageView photo,imgPhoto,img ,imageView ;
        private TextView txtName, txtGoodAt, txtIntro, imgGener, txtzizhi,jibie;
        private Button btn_bind ,btn_talk;
        String CoachUrl;
        private HorizontalListView listView;
        private CoachImgsAdapter imgsAdapter;
        private int it,exact;
         List<String> tupian=new ArrayList<String>();
         String []imageUrls=new String[]{};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_coach_info);
        exact=SharedPreferencesUtil.getInt(this, com.wee.aircoach_user.Constant.USERTIME);
        String CoachId= getIntent().getStringExtra("Coachid");
        CoachUrl=Constant.COACH_INFO+ MD5Util.md5(exact)+"&id="+CoachId;
        /**接口解析*/
        initView();

    }

    private void init() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                gethttp();
            }
        }).start();
    }

    @Override
    protected void onResume() {
        super.onResume();
        init();
    }

    /** 解析字段 */
    public void gethttp() {
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.send(HttpRequest.HttpMethod.GET, CoachUrl, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String str = responseInfo.result;
                Gson gs = new Gson();
                JsonObject jo = gs.fromJson(str, JsonObject.class);
                JsonElement je = jo.get("status");
                String status = je.getAsString();
                if ("ok".equals(status)) {
                    JsonObject object = jo.getAsJsonObject("data");
                    details = gs.fromJson(object, Coach_details.class);
                    updateCoachView();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                System.out.println(e.getMessage());
            }
        });
    }
    private void initView() {
        imageView = (ImageView)findViewById(R.id.plan_bg);
        it = SharedPreferencesUtil.getInt(CoachInfoActivity.this, Constant.USERID);
        com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage("drawable://" + R.drawable.coach_info_bg, imageView);
        findViewById(R.id.back).setOnClickListener(this);
        btn_bind= (Button) findViewById(R.id.btn_bind);
        btn_bind .setOnClickListener(this);
        btn_talk=(Button) findViewById(R.id.btn_talk);
        btn_talk.setOnClickListener(this);
        photo = (ImageView) findViewById(R.id.photo);
        img = (ImageView)findViewById(R.id.img);
        imgPhoto = (ImageView)findViewById(R.id.photo);
        txtName = (TextView)findViewById(R.id.name);
        imgGener = (TextView)findViewById(R.id.gener);
        txtzizhi = (TextView)findViewById(R.id.zizhi);
        txtGoodAt = (TextView)findViewById(R.id.shanchang);
        txtIntro = (TextView)findViewById(R.id.intro);
        jibie = (TextView)findViewById(R.id.jibie);
        listView = (HorizontalListView)findViewById(R.id.list);
    }

    private void updateCoachView(){
        tupian.clear();
        //需要判定是否是 绑定教练 然后按钮显示
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.GET,
                Constant.ISMY_COCAH + "?token=" + MD5Util.md5(exact) + "&coachId=" +details.getId() + "" + "&userId=" + it + "&ver"+new Random().nextInt(9999),
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }


                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String str = responseInfo.result;
                        Gson gs = new Gson();
                        JsonObject jo = gs.fromJson(str, JsonObject.class);
                        JsonElement je = jo.get("status");
                        String status = je.getAsString();
                        if ("ok".equals(status)) {
                            JsonObject object = jo.getAsJsonObject("data");
                            IsMy_plan plan = gs.fromJson(object, IsMy_plan.class);
                            if (plan.getRes().equals("yes")) {
                                btn_bind.setVisibility(View.GONE);
                                btn_talk.setVisibility(View.VISIBLE);
                            } else {
                                btn_bind.setVisibility(View.VISIBLE);
                                btn_talk.setVisibility(View.GONE);
                            }

                        }
                    }

                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Toast.makeText(CoachInfoActivity.this, "有问题", Toast.LENGTH_SHORT).show();
                    }
                });
        if(details.getFigure()!=null &&details.getFigure().length()!=0){
            MyApplication.getInstance().getImageLoader().get(details.getFigure(), ImageLoader.getImageListener(imgPhoto, R.drawable.coach_no, R.drawable.coach_no),200,200);
        }
        if(details.getGender()!=null){
            if(details.getGender().equals("male")){
                imgGener.setText("男");
                img.setImageResource(R.drawable.man);
            }else{
                img.setImageResource(R.drawable.woman);
                imgGener.setText("女");
            }
        }
        /**图片的问题*/
        for (int i=0;i<details.getImage().size();i++
                ){
            tupian.add(details.getImage().get(i).getUrl());
        }
        if (tupian.size()!=0&&tupian!=null){
            imageUrls= tupian.toArray(new String[tupian.size()]);
            imgsAdapter = new CoachImgsAdapter(this, tupian);
            listView.setAdapter(imgsAdapter);
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            //        Toast.makeText(CoachInfoActivity.this, "" + position, Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(CoachInfoActivity.this, ImagePagerActivity.class);
                    //图片url,为了演示这里使用常量，一般从数据库中或网络中获取
                    intent.putExtra("images", imageUrls);
                    intent.putExtra("image_index", position);
                    startActivity(intent);
                }
            });
        }else{
            listView.setVisibility(View.GONE);
        }


        /****/
        txtGoodAt.setText(""+details.getSpecialty());
        txtzizhi.setText("" + details.getTitle());
        txtName.setText("" + details.getName());
        jibie.setText("" + details.getTitle());
        txtIntro.setText("" + details.getDiscription());
    }

    private void bindCoach() {

        RequestParams params = new RequestParams();
        params.addBodyParameter("token", "" + MD5Util.md5(exact));
        params.addBodyParameter("userId", "" + it);
        params.addBodyParameter("coachId", "" + details.getId());
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST,
                Constant.BIND_COACH,
                params,
                new RequestCallBack<String>() {

                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String str = responseInfo.result;
                        JSONObject json;
                        try {
                            json = new JSONObject(str);
                            if (json.getString("status").equals("ok")) {
                                //  SharedPreferencesUtil.setInt(CoachInfoActivity.this,Constant.NUM,0);
                                Toast.makeText(CoachInfoActivity.this, "绑定成功", Toast.LENGTH_LONG).show();
                                btn_bind.setVisibility(View.GONE);
                                btn_talk.setVisibility(View.VISIBLE);
                            } else {
                                Toast.makeText(CoachInfoActivity.this, "绑定失败1", Toast.LENGTH_LONG).show();
                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {

                    }
                });
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.back){
          startActivity(new Intent(CoachInfoActivity.this,MainActivity.class));
            onDestroy();
        }else if(v.getId() == R.id.btn_bind){
            bindCoach();
        }else if(v.getId() == R.id.btn_talk){
        //    startActivity(new Intent(CoachInfoActivity.this,ConsultPostActivity.class));
            chat();
        }else if (v.getId()== R.id.photo){

        }
    }

    private void chat() {
        if(details==null){
            return;
        }
        final String pwd = "abc123";
        final String coach = "coach_"+details.getId();
        final String user1 = "user_"+it;

        UserUtils.getUserInfo(coach).setNick(details.getName());
        UserUtils.getUserInfo(coach).setAvatar(details.getFigure());
        if (DemoHXSDKHelper.getInstance().isLogined()) {//进入主页面
            Intent intent = new Intent(this, ChatActivity.class);
            intent.putExtra("userId", coach);
            startActivity(intent);
          //  finish();
            return;
        }else {
            EMChatManager.getInstance().login(user1, pwd, new EMCallBack() {
                @Override
                public void onSuccess() {
                    Intent intent = new Intent(CoachInfoActivity.this, ChatActivity.class);
                    intent.putExtra("userId", coach);
                    startActivity(intent);
               //     finish();
                }
                @Override
                public void onProgress(int arg0, String arg1) {
                    // TODO Auto-generated method stub
                }
                @Override
                public void onError(int arg0, String arg1) {
                    // TODO Auto-generated method stub

                }
            });
        }
    }

}
